using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class Character : MonoBehaviour
{
  // Start is called before the first frame update
  [Header("基本属性")]
  public float maxHealth;
  public float curHealth;

  [Header("受伤无敌")]
  public float invulnerableDuration;
  public float invulnerableCounter;
  public bool invulnerable;
  [Header("事件")]
  public UnityEvent<Transform> onTakeDamage;
  public UnityEvent onDie;

  /// <summary>
  /// Start is called on the frame when a script is enabled just before
  /// any of the Update methods is called the first time.
  /// </summary>
  private void Start()
  {
    curHealth = maxHealth;
  }

  /// <summary>
  /// Update is called every frame, if the MonoBehaviour is enabled.
  /// </summary>
  private void Update()
  {
    if (invulnerable)
    {
      invulnerableCounter -= Time.deltaTime;
      // Time.deltaTime 时间的修正，执行上一帧所花的时间，在性能不同的机器上，可能有差别
      if (invulnerableCounter <= 0)
      {
        invulnerable = false;
        invulnerableCounter = 0;
      }
    }
  }

  public void TakeDamage(Attack attacker)
  {
    if (invulnerable) return;

    if (curHealth > attacker.damage)
    {
      // 扣血
      curHealth -= attacker.damage;
      // 无敌
      TriggerInvulnerable();
      // 触发OnTakeDamage事件
      onTakeDamage?.Invoke(attacker.transform);
    }
    else
    {
      curHealth = 0;
      TriggleDeath(); // 触发死亡方法
      onDie?.Invoke(); // 触发死亡事件 与上面的相比，这个好像更好用一点
    }

  }

  /// <summary>
  /// 触发死亡
  /// </summary>
  public void TriggleDeath()
  {

  }

  /// <summary>
  /// 触发无敌
  /// </summary>
  private void TriggerInvulnerable()
  {
    if (!invulnerable)
    {
      invulnerable = true;
      invulnerableCounter = invulnerableDuration;
    }
  }
}
